const host = "https://smartgym.ocmcom.com/smallapp/Member";
var MD5 = require("md5.js");
function request(obj) {
  var timestamp = Date.parse(new Date()) / 1000;
  var key = "ocmcom_me";
  var url = host + obj.url
  obj.data.time = timestamp;
  obj.data.sign = MD5.hexMD5(key + "_" + timestamp);
  console.log("net request", obj);
  wx.request({
    url: url,
    data: obj.data,
    method: "POST",
    success: function (res) { console.log("net success:", res); if (obj.success) obj.success(res); },
    fail: function (res) { console.log("net fail:", res); if (obj.fail) obj.fail(res); },
    complete: function (res) { if (obj.complete) obj.complete(res); },
  })

}

function uploadFile(obj) {
  var timestamp = Date.parse(new Date()) / 1000;
  var key = "ocmcom_me";
  var url = host + obj.url
  obj.formData.time = timestamp;
  obj.formData.sign = MD5.hexMD5(key + "_" + timestamp);
  console.log("net uploadFile", obj);
  wx.uploadFile({
    url: url, //仅为示例，非真实的接口地址
    filePath: obj.filePath,
    name: obj.name,
    formData: obj.formData,
    success: function (res) {
      console.log("net success:", res)
      if (obj.success) obj.success(res);
    }, fail(res) {
      console.log("net fail:", res)
      if (obj.fail) obj.fail(res);
    }, complete() {
      if (obj.complete) obj.complete();
    }
  })
}

function handleForward(url, openType = 4) {
  let forwardObj = {
    url: url,
    success() {
      let t = setTimeout(function () {
        gb.isNavigating = false;
        clearTimeout(t);
      }, 1000);
    }
  };
  if (!gb.isNavigating) {
    gb.isNavigating = true;

    switch (openType) {
      case 1:   // 切换tab
        wx.switchTab(forwardObj);
        break;
      case 2:    // 重定向
        wx.redirectTo(forwardObj);
        break;
      case 3:    // 重定向
        wx.reLaunch(forwardObj);
        break;
      default:            // 正常跳转
        wx.navigateTo(forwardObj);
        break;
    }
  }
}

module.exports = {
  request: request,
  uploadFile: uploadFile,
  go: handleForward
}